package com.jsb.laundry.controller.factory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.jsb.laundry.common.enums.OrderStatus;
import com.jsb.laundry.common.enums.ReturnStatusCode;
import com.jsb.laundry.common.response.ResultPage;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.aliyun.AliOSSUtil;
import com.jsb.laundry.common.utils.excel.AttachmentResponse;
import com.jsb.laundry.common.utils.excel.ExcelResponse;
import com.jsb.laundry.common.utils.http.EncryptUtil;
import com.jsb.laundry.common.utils.sf.SFMsgDataBuilder;
import com.jsb.laundry.common.utils.sf.SFServiceCodeEnum;
import com.jsb.laundry.common.utils.sf.SFUtil;
import com.jsb.laundry.dao.factory.LaundryFactoryDao;
import com.jsb.laundry.model.factory.*;
import com.jsb.laundry.service.factory.LaundryFactoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 洗衣工厂模块
 *
 * @data 2023/3/14 10:06
 */
@RestController
@RequestMapping("/laundryFactory")
public class FactoryController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FactoryController.class);
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private LaundryFactoryService laundryFactoryService;

    @Resource
    private LaundryFactoryDao laundryFactoryDao;

    /**
     * 订单状态变更日志
     *
     * @param orderId
     * @param status
     */
    public void addOrderStatusLog(String orderId, OrderStatus status, String orderDirection) {
        int var0 = laundryFactoryDao.addOrderStatusLog(orderId, status.getCode(), status.getMsg(), orderDirection);
        LOGGER.info("订单:{},状态变更日志:{},订单方向:{}", orderId, status, orderDirection);
    }

    /**
     * 工厂账号密码登录
     *
     * @param sysFactory
     * @return
     */
    @PostMapping("/login")
    public WebResponse login(@RequestBody SysFactory sysFactory) {
        String factoryId = laundryFactoryDao.factoryLogin(sysFactory);
        if (JSBUtil.isEmptyString(factoryId)) {
            return WebResponse.success(ReturnStatusCode.ACCOUNT_NOT_FOUND.getCode(), ReturnStatusCode.ACCOUNT_NOT_FOUND.getMsg());
        }
        HashMap hashMap = laundryFactoryDao.shopsInfo(factoryId);
        if (hashMap == null) {
            return WebResponse.success(ReturnStatusCode.LOGIN_FAIL.getCode(), ReturnStatusCode.LOGIN_FAIL.getMsg());
        }


        String id = String.valueOf(hashMap.get("shops_id"));
        //token过期时间戳
        long tokenExpireTimestamp = LocalDateTime.now().plusDays(30).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        //TODO token生成处(uuid + userId() + timestamp(token过期的时间戳) )
        String token = "factory_Authorization: " + JSBUtil.generateUUID() + ". " + EncryptUtil.Base64Tool.base64Encode(id) + ". " + EncryptUtil.Base64Tool.base64Encode(String.valueOf(tokenExpireTimestamp));
        //存在redis数据库
        redisTemplate.opsForValue().set(token, id, 30, TimeUnit.DAYS);
        hashMap.put("token", token);

        return WebResponse.successData(hashMap);
    }

    /**
     * 核心 入库出库 列表数据
     *
     * @param orderInfoDtos
     * @return
     */
    @PostMapping("/inAndOutDataList")
    public WebResponse inAndOutDataList(@RequestBody OrderInfoDtos orderInfoDtos) {
        //开启分页
        PageHelper.startPage(orderInfoDtos.getPageNum(), orderInfoDtos.getPageSize());

        List<OrderInfoDtos> res = laundryFactoryDao.inAndOutDataList(orderInfoDtos);

        ResultPage<List<OrderInfoDtos>> returnData = new ResultPage<>(res);

        return WebResponse.successData(returnData);
    }

    /**
     * 检查入库页面时
     *
     * @param orderInfoDtos
     * @return
     */
    @PostMapping("/orderInfoShops")
    public WebResponse orderInfoShops(@RequestBody OrderInfoDtos orderInfoDtos) {
        if (JSBUtil.isEmptyString(orderInfoDtos.getPayId()) || orderInfoDtos.getSubOrderIds() == null || orderInfoDtos.getSubOrderIds().size() == 0) {
            return WebResponse.failOfParameter();
        }
        OrderInfoShops orderInfoShops = laundryFactoryService.orderInfoShops1(orderInfoDtos.getPayId(), orderInfoDtos.getSubOrderIds());
        return WebResponse.successData(orderInfoShops);
    }

    /**
     * 订单进入工厂
     *
     * @param orderInfoDtos
     * @return
     */
    @PostMapping("/orderEnterFactory1")
    public WebResponse orderEnterFactory(@RequestBody OrderInfoDtos orderInfoDtos) {
        if (JSBUtil.isEmptyString(orderInfoDtos.getPayId())) {
            return WebResponse.failOfParameter();
        }
        String payId = orderInfoDtos.getPayId();
        JsbOrdersFactory jsbOrdersFactory = laundryFactoryDao.getOrdersFactoryInfo(payId);
        if (jsbOrdersFactory == null) { //不存在时，则入库

            /**
             * 入工厂表 jsb_orders_factory
             */
            JsbOrders orderInfo = laundryFactoryDao.getOrderInfo(payId);
            JsbOrdersFactory ordersFactory = new JsbOrdersFactory();
            ordersFactory.setOrderId(payId).setUserId(orderInfo.getUserId()).
                    setFactoryId(orderInfo.getShopId())
                    .setFactoryOrdersStatus("1").setType(orderInfo.getShippingType());
            Integer var0 = laundryFactoryDao.addOrderFactory(ordersFactory);


            /**
             * 入工厂表 jsb_orders_factory_item
             */
            List<JsbOrdersItem> subOrderList = laundryFactoryDao.getSubOrderList(payId);
            List<JsbOrdersFactoryItem> jsbOrdersFactoryItem = subOrderList.stream()
                    .map(jsbOrdersItem -> {
                        JsbOrdersFactoryItem item = new JsbOrdersFactoryItem();
                        item.setOrderFactoryId(var0)
                                .setProductId(jsbOrdersItem.getProductId())
                                .setOrderId(jsbOrdersItem.getOrderId())
                                .setSubOrderId(jsbOrdersItem.getSubOrderId());
                        return item;
                    })
                    .collect(Collectors.toList());

            int var1 = laundryFactoryDao.addOrderFactoryItem(jsbOrdersFactoryItem);
            return WebResponse.success();
        }

        return WebResponse.success("该订单不存在或已进入工厂");
    }

    /**
     * 订单进入工厂  subOrderIds
     */
    @PostMapping("/orderEnterFactory")
    @Transactional
    public WebResponse orderEnterFactory1(@RequestBody OrderInfoDtos orderInfoDtos) {
        if (JSBUtil.isEmptyCollection(orderInfoDtos.getSubOrderIds())) {
            return WebResponse.failOfParameter();
        }
        List<String> subOrderIdLs = new ArrayList(new HashSet(orderInfoDtos.getSubOrderIds()));
        List<JsbOrdersFactoryItem> factoryItemSubOrder = subOrderIdLs.stream()
                .map(subOrderId -> new JsbOrdersFactoryItem().setSubOrderId(subOrderId))
                .collect(Collectors.toList());

        /**
         * TODO 主要获取 JsbOrdersItem中 subOrderId、orderId
         */
        List<String> subOrderIdList = factoryItemSubOrder.stream().map(JsbOrdersFactoryItem::getSubOrderId).collect(Collectors.toList());
        List<JsbOrdersItem> subOrderList1 = laundryFactoryDao.getSubOrderItemList(subOrderIdList);
        //让 factoryItemSubOrder 可以拿到orderId
        subOrderList1.forEach(jsbOrdersItem ->
                factoryItemSubOrder.stream()
                        .filter(jsbOrdersFactoryItem ->
                                jsbOrdersFactoryItem.getSubOrderId().equals(jsbOrdersItem.getSubOrderId()))
                        .findFirst()
                        .ifPresent(jsbOrdersFactoryItem ->
                                jsbOrdersFactoryItem.setOrderId(jsbOrdersItem.getOrderId()))
        );
        //主订单id
        List<String> orderIdList = subOrderList1.stream().map(JsbOrdersItem::getOrderId).distinct().collect(Collectors.toList());
        //已入工厂订单主表的订单
        List<JsbOrdersFactory> ordersFactoryItemList = laundryFactoryDao.getOrdersFactoryInfo1(orderIdList);

        //当前还未入工厂子表的订单
        List<JsbOrdersFactoryItem> noInFactoryOrderList = factoryItemSubOrder.stream()
                .filter(item -> ordersFactoryItemList.stream().noneMatch(orderItem -> orderItem.getOrderId().equals(item.getOrderId())))
                .collect(Collectors.toList());

        /**
         * TODO 入工厂表 jsb_orders_factory
         */
        if (!JSBUtil.isEmptyCollection(noInFactoryOrderList)) { //不存在的，则入库

            List<JsbOrders> orderInfo = laundryFactoryDao.getOrderInfo1(orderIdList);
            List<JsbOrders> itemOrderInfo = laundryFactoryDao.getOrderInfo2(subOrderIdList);
            orderInfo.forEach(jsbOrders -> {
                itemOrderInfo.stream()
                        .filter(orders -> orders.getOrderId().equals(jsbOrders.getOrderId()))
                        .findFirst()
                        .ifPresent(orders -> jsbOrders.setNextToId(orders.getNextToId()));
            });


            List<JsbOrdersFactory> ordersFactoryList = orderInfo.stream().map(orderInfoItem -> {
                JsbOrdersFactory ordersFactory = new JsbOrdersFactory();
                ordersFactory.setOrderId(orderInfoItem.getOrderId())
                        .setUserId(orderInfoItem.getUserId())
                        .setShopId(orderInfoItem.getShopId())
                        .setFactoryId(orderInfoItem.getNextToId())
                        .setFactoryOrdersStatus("1")
                        .setType(orderInfoItem.getShippingType());
                return ordersFactory;
            }).collect(Collectors.toList());

            Integer var0 = laundryFactoryDao.addOrderFactory1(ordersFactoryList);
            // 把插入id放入list中后面子表要用
            noInFactoryOrderList.stream()
                    .forEach(jsbOrdersFactoryItem -> ordersFactoryList.stream()
                            .filter(jsbOrdersFactory -> jsbOrdersFactory.getOrderId().equals(jsbOrdersFactoryItem.getOrderId()))
                            .findFirst()
                            .ifPresent(jsbOrdersFactory -> jsbOrdersFactoryItem.setId(jsbOrdersFactory.getId())));

            LOGGER.info("订单入工厂表 jsb_orders_factory：{}", ordersFactoryList);
        }


        //已进入工厂子表的子订单
        List<JsbOrdersFactoryItem> ordersFactoryItems = laundryFactoryDao.getOrdersFactoryItem(factoryItemSubOrder);

        //当前还未入工厂子表的订单
        List<JsbOrdersFactoryItem> noInFactoryOrderItemList = factoryItemSubOrder.stream()
                .filter(item -> ordersFactoryItems.stream().noneMatch(orderItem -> orderItem.getSubOrderId().equals(item.getSubOrderId())))
                .collect(Collectors.toList());

        /**
         * TODO 入工厂表 jsb_orders_factory_item
         */
        if (!JSBUtil.isEmptyCollection(noInFactoryOrderItemList)) { //不存在的订单，则入库

            //父订单入入工厂主表了，当前noInFactoryOrderItemList就没有 id ，无意义的字段考虑移除
            List<JsbOrdersFactoryItem> filteredList = noInFactoryOrderItemList.stream()
                    .filter(item -> item.getId() == null || "".equals(item.getId()))
                    .collect(Collectors.toList());
            if (!JSBUtil.isEmptyCollection(filteredList)) {
                List<JsbOrdersFactory> alreadyIntoFactoryOrder = laundryFactoryDao.getOrdersFactoryInfo1(orderIdList);
                noInFactoryOrderItemList.forEach(jsbOrdersFactoryItem ->
                        alreadyIntoFactoryOrder.stream()
                                .filter(jsbOrdersFactory ->
                                        jsbOrdersFactory.getOrderId().equals(jsbOrdersFactoryItem.getOrderId()))
                                .findFirst()
                                .ifPresent(jsbOrdersFactory ->
                                        jsbOrdersFactoryItem.setId(jsbOrdersFactory.getId()))
                );
            }

            List<String> subOrderIds = noInFactoryOrderItemList.stream().map(JsbOrdersFactoryItem::getSubOrderId).collect(Collectors.toList());

            List<JsbOrdersItem> subOrderList = laundryFactoryDao.getSubOrderItemList(subOrderIds);
            List<JsbOrdersFactoryItem> noInFactoryOrderItemList1 = noInFactoryOrderItemList;
            List<JsbOrdersFactoryItem> jsbOrdersFactoryItem = IntStream.range(0, subOrderList.size())
                    .mapToObj(index -> {
                        JsbOrdersFactoryItem item = new JsbOrdersFactoryItem();
                        JsbOrdersItem jsbOrdersItem = subOrderList.get(index);
                        JsbOrdersFactoryItem noInFactoryOrderItem = noInFactoryOrderItemList1.get(index);

                        item.setOrderFactoryId(noInFactoryOrderItem.getId())
                                .setProductId(jsbOrdersItem.getProductId())
                                .setOrderId(jsbOrdersItem.getOrderId())
                                .setSubOrderId(jsbOrdersItem.getSubOrderId());

                        return item;
                    })
                    .collect(Collectors.toList());

            int var1 = laundryFactoryDao.addOrderFactoryItem(jsbOrdersFactoryItem);
            LOGGER.info("订单入工厂表 jsb_orders_factory_item：{}", jsbOrdersFactoryItem);
            return WebResponse.success();
        }

        return WebResponse.success("该订单不存在或已进入工厂");
    }


    /**
     * 检查操作
     *
     * @param orderInfoDtos
     * @return
     */
    @PostMapping("/updInspect")
    public WebResponse updInspect(@RequestBody OrderInfoDtos orderInfoDtos) {
        if (JSBUtil.isEmptyString(orderInfoDtos.getOrderId()) || JSBUtil.isEmptyString(orderInfoDtos.getInspect())
                || JSBUtil.isEmptyString(orderInfoDtos.getFlag())) {
            return WebResponse.failOfParameter();
        }
        int sss = laundryFactoryService.updInspect(orderInfoDtos.getOrderId(), orderInfoDtos.getInspect(), orderInfoDtos.getFlag());
//        if (sss > 0) {
//            if ("0".equals(orderInfoDtos.getFlag())) { //入库状态变更日志
//                addOrderStatusLog(orderInfoDtos.getOrderId(),);
//            }else { //出库状态变更日志
//                addOrderStatusLog(orderInfoDtos.getOrderId(),);
//            }
//        }
        return WebResponse.successData(sss);
    }


    /**
     * 订单状态变更
     *
     * @param orderInfoDtos
     * @return
     */
    @PostMapping("/updOrderStatus")
    public WebResponse sss1(@RequestBody OrderInfoDtos orderInfoDtos) {
        if (JSBUtil.isEmptyString(orderInfoDtos.getOrderId()) || JSBUtil.isEmptyString(orderInfoDtos.getFlag())  || JSBUtil.isEmptyString(orderInfoDtos.getOrderStatus())
                || JSBUtil.isEmptyString(orderInfoDtos.getOrderDirection()) || JSBUtil.isEmptyCollection(orderInfoDtos.getSubOrderIds())) {
            return WebResponse.failOfParameter();
        }
        String orderDirection = orderInfoDtos.getOrderDirection();
        orderInfoDtos.setSubOrderId(orderInfoDtos.getSubOrderIds().get(0));
        int var0 = laundryFactoryDao.updOrderStatus(orderInfoDtos);
        /**
         * 入库订单状态调整为8 洗护中
         */
        if ("1".equals(orderInfoDtos.getOrderDirection()) && "2".equals(orderInfoDtos.getOrderStatus())) {
            laundryFactoryDao.updOrderFactoryStatus(orderInfoDtos.getOrderId(), "0");
        }

        String orderId = orderInfoDtos.getOrderId();
        String flag = orderInfoDtos.getFlag();
        int var1 = laundryFactoryDao.getCheckIng(orderId, flag);
        /**
         * flag 0已入库  1已出库
         * 全部检查后
         * jsb_orders_factory 中 factory_orders_status 2 已入库 4已出库
         * jsb_orders 中factory_status 1已入库  2已出库
         */
        if (var1 == 0) {
            laundryFactoryDao.updOrderFactoryStatus(orderId, flag);
            laundryFactoryDao.updFactoryOrderStatus(orderId, flag);
        }


        return WebResponse.successData(var0);
    }

    /**
     * 获取使用站点
     *
     * @return
     */
    @PostMapping("/site")
    public WebResponse site() {
        List<Site> site = laundryFactoryService.site();
        return WebResponse.successData(site);
    }

    /**
     * 洗衣瑕疵、配饰 等修改
     *
     * @param findByList
     * @return
     */
    @PostMapping("/updOrderDetails")
    public WebResponse updOrderDetails(@RequestBody FindByList findByList) {
        int i = laundryFactoryService.updOrderDetails(findByList);
        return WebResponse.successData(i);
    }


    /**
     * 工厂出库入库检查 订单中添加检查图片( orderId、picListStr:“asd,gfu,fhh”,flag:(0:入库，1：出库) )
     */
    @PostMapping("checkClothesEnterOrOut")
    public WebResponse checkClothesEnterOrOut(@RequestBody String data) {
        LOGGER.info("工厂出库入库检查 订单中添加检查图片,{}", data);
        JSONObject jsonObject = JSON.parseObject(data);
        String orderId = jsonObject.getString("orderId");
        String flag = jsonObject.getString("flag");
        String picListStr = jsonObject.getString("picListStr");
        if (JSBUtil.isEmptyString(orderId) || JSBUtil.isEmptyString(flag)
                || JSBUtil.isEmptyString(picListStr)) {
            return WebResponse.failOfParameter();
        }
        int i = laundryFactoryService.checkClothesEnterOrOut(orderId, picListStr, flag);
        return WebResponse.successData(i);
    }

    /**
     * 确认出库时,下单 (userId、payId、num(衣物数量)、type（1：骑手送达，2：顺丰送达）)
     */
    @PostMapping("factoryOrderBack")
    public WebResponse factoryOrderBack(@RequestBody JSONObject jsonObject) {
        LOGGER.info("确认出库时,下单:{}", jsonObject);
        String userId = jsonObject.getString("userId");
        String payId = jsonObject.getString("payId");
        Integer num = jsonObject.getInteger("num");
        String type = jsonObject.getString("type");
        List subOrderIds = jsonObject.getJSONArray("subOrderIds");
        if (JSBUtil.isEmptyString(userId) || JSBUtil.isEmptyString(payId)
                || JSBUtil.isEmptyString(type) || JSBUtil.isEmptyObject(num) || JSBUtil.isEmptyCollection(subOrderIds)) {
            return WebResponse.failOfParameter();
        }
        int var0 = laundryFactoryService.factoryOrderBack(type, userId, payId, num, subOrderIds);
        return WebResponse.successData(var0);
    }

    /**
     * 返回要打印的水洗标字段(payId)
     *
     * @param
     * @return
     */
    @PostMapping("printWaterWashLabel")
    public WebResponse printWaterWashLabel(@RequestBody OrderInfoDtos orderInfoDtos) {
        if (orderInfoDtos.getPayId() == null || orderInfoDtos.getPayId().equals("")) {
            return WebResponse.successData("请输入payId");
        }
        OrderInfoShops orderInfoShops = laundryFactoryService.orderInfoShops1(orderInfoDtos.getPayId(), orderInfoDtos.getSubOrderIds());
        return WebResponse.successData(orderInfoShops);
    }

    /**
     * 根据物流id获取获取子订单状态( tpId \ orderDirection)
     *
     * @return
     */
    @PostMapping("getSubOrderInfoByFulfillmentsId")
    public WebResponse getSubOrderInfoByFulfillmentsId(@RequestBody OrderInfoDtos orderInfoDtos) {
        if (JSBUtil.isEmptyString(orderInfoDtos.getTpId())) {
            return WebResponse.failOfParameter();
        }
        HashMap res = laundryFactoryDao.getSubOrderInfoByFulfillmentsId(orderInfoDtos);
        return WebResponse.successData(res);
    }

    /**
     * 查看物流信息
     * payId:["p1","p2"]
     */
    @RequestMapping(value = "/showSFRoutes")
    public WebResponse showSFRoutes(@RequestBody String data) {
        LOGGER.info("查看物流信息,{}", data);
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONArray payIdList = jsonObject.getJSONArray("payId");
        //请求参数判空
        if (JSBUtil.isEmptyCollection(payIdList)) {
            return WebResponse.failOfParameter();
        }
        String logisticsTrackMsgData = SFMsgDataBuilder.getLogisticsTrackMsgData(payIdList);
        String sfResponse = SFUtil.SFRequest(SFServiceCodeEnum.EXP_RECE_SEARCH_ROUTES.name(), logisticsTrackMsgData);
        return WebResponse.successData(JSONObject.parseObject(sfResponse));
    }

    /**
     * 颜色的操作
     * {
     * "op":"0",
     * name:"蓝色"，
     * c："#kgnkdjn"
     * uuid:"ab" (修改,删除时传)
     * }
     *
     * @param data
     * @return
     */
    @PostMapping("opColour")
    public WebResponse opColour(@RequestBody String data) {
        LOGGER.info("颜色的操作:{}", data);
        JSONObject jsonObject = JSON.parseObject(data);
        String op = jsonObject.getString("op"); //操作 0：添加，1：修改,2:删除
        String name = jsonObject.getString("name");
        String c_16 = jsonObject.getString("c");
        String uuid = jsonObject.getString("uuid");
        int var0 = laundryFactoryService.opColour(op, name, c_16, uuid);
        return WebResponse.successData(var0);
    }

    /**
     * 配饰的操作(op、name、uuid)
     *
     * @param data
     * @return
     */
    @PostMapping("opACC")
    public WebResponse opACC(@RequestBody String data) {
        LOGGER.info("配饰的操作:{}", data);
        JSONObject jsonObject = JSON.parseObject(data);
        String op = jsonObject.getString("op"); //操作 0：添加，1：修改,2:删除
        String name = jsonObject.getString("name");
        String uuid = jsonObject.getString("uuid");
        int var0 = laundryFactoryService.opACC(op, name, uuid);
        return WebResponse.successData(var0);
    }

    /**
     * 品牌的操作op、name、pic、uuid
     *
     * @param data
     * @return
     */
    @PostMapping("opBrand")
    public WebResponse opBrand(@RequestBody String data) {
        LOGGER.info("品牌的操作:{}", data);
        JSONObject jsonObject = JSON.parseObject(data);
        String op = jsonObject.getString("op"); //操作 0：添加，1：修改,2:删除
        String name = jsonObject.getString("name");
        String pic = jsonObject.getString("pic");
        String uuid = jsonObject.getString("uuid");
        int var0 = laundryFactoryService.opBrand(op, name, pic, uuid);
        return WebResponse.successData(var0);
    }

    /**
     * 洗后效果的操作（op、name、uuid）
     *
     * @param data
     * @return
     */
    @PostMapping("opEffect")
    public WebResponse opEffect(@RequestBody String data) {
        LOGGER.info("洗后效果的操作:{}", data);
        JSONObject jsonObject = JSON.parseObject(data);
        String op = jsonObject.getString("op"); //操作 0：添加，1：修改,2:删除
        String name = jsonObject.getString("name");
        String uuid = jsonObject.getString("uuid");
        int var0 = laundryFactoryService.opEffect(op, name, uuid);
        return WebResponse.successData(var0);
    }

    /**
     * 瑕疵的操作（op、t）
     * op操作 0：添加，1：修改,2:删除;
     * t添加目标，父级操作0,子级操作1
     *
     * @param data
     * @return
     */
    @PostMapping("opFlaw")
    public WebResponse opFlaw(@RequestBody String data) {
        LOGGER.info("洗后效果的操作:{}", data);
        JSONObject jsonObject = JSON.parseObject(data);
        String op = jsonObject.getString("op"); //操作 0：添加，1：修改,2:删除
        String t = jsonObject.getString("t"); //父级操作0,子级操作1
        String pId = jsonObject.getString("pid"); //父级id
        String uuid = jsonObject.getString("uuid"); //自己id
        String name = jsonObject.getString("name"); //通用名
        int var0 = laundryFactoryService.opFlaw(op, t, name, uuid, pId);
        return WebResponse.successData(var0);
    }

    public static List packageList(List<FindByList> byList) {
        List<FindByList> result = byList.stream()
                .collect(Collectors.groupingBy(FindByList::getPId)) // 按pId分组
                .entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey()) // 按 pId 排序
                .map(entry -> {
                    FindByList p = new FindByList();
                    p.setPId(entry.getKey());
                    p.setPName(entry.getValue().get(0).getPName());
                    p.setSub(entry.getValue().stream()
                            .map(item -> {
                                FindByList c = new FindByList();
                                c.setName(item.getName());
                                c.setUuid(item.getUuid());
                                return c;
                            }).collect(Collectors.toList()));
                    return p;
                })
                .collect(Collectors.toList());
        return result;
    }


    /**
     * 上传图片
     *
     * @param file
     * @param
     * @return
     */
    @PostMapping("/categoryImg")
    public String addUserImg(@RequestParam(value = "file") MultipartFile file) {
        if (file.isEmpty() || !isFileValid(file)) {
            return "上传的图片无法识别";
        }
        String URL = AliOSSUtil.uploadFile(file);
        LOGGER.info("文件的访问地址===>" + URL);
        return URL;
    }

    private boolean isFileValid(MultipartFile file) {
        // 这里可以根据实际需求添加文件验证的逻辑
        // 例如，可以检查文件类型、文件大小等

        // 示例：验证文件类型是否为图片
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return false;
        }

        return true;
    }

    /**
     * 2.0工厂 查询查账主订单列表
     */
    @PostMapping("orderInfoList")
    public WebResponse orderInfoList(@RequestBody FactoryOrderInfo info) {
        PageHelper.startPage(info.getPageNum(), info.getPageSize());
        List<FactoryOrderInfo> byOrderInfo = laundryFactoryDao.orderInfoList(info);
        return WebResponse.successData(byOrderInfo);
    }

    /**
     * 2.0 账单下载
     *
     * @param request
     * @param response
     */
    @PostMapping("downloadExcelV2")
    public void downloadExcelV2(HttpServletRequest request, HttpServletResponse response, @RequestBody FactoryOrderInfo info) {
        LOGGER.info("请求参数 request" + request + "请求参数 response" + response + "请求参数 jsonObject" + info);
        ExcelResponse xls = null;
        final String[] EXCEL_HEAD = {"衣物类型", "洗护方式", "数量", "价格"};
        try {
            xls = new ExcelResponse(request, response, "订单查账表" + ".xls");
            xls.selectSheet("统计");
            xls.writeTitles(EXCEL_HEAD);
            //逻辑  list

//            PageHelper.startPage(pageNum, pageSize);
            List<FactoryOrderInfo> byOrderInfos = laundryFactoryDao.downloadExcelV2(info);
            //遍历到excel
            for (FactoryOrderInfo list : byOrderInfos) {
                xls.writeRecord(
                        list.getGoodsTitle(),
                        list.getWashType(),
                        list.getCount(),
                        list.getFactoryPrice()
                );
            }
        } catch (Exception e) {

            LOGGER.error("列表下载异常" + e.getMessage());
            try {
                AttachmentResponse.writeDownloadErrorResponse(response, "表列表下载异常");
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        } finally {
            if (xls != null) {

                xls.dump();
                xls.close();
            }
        }
    }


    /**
     * 获取所有衣物
     *
     * @return
     */
    @PostMapping("goodsList")
    public WebResponse goodsList() {

        List<GoodsInfo> goodsInfos = laundryFactoryService.goodsList();

        return WebResponse.successData(goodsInfos);
    }

    /**
     * 查询查账主订单
     */
    @PostMapping("orderInfo")
    public WebResponse orderInfo(@RequestBody JSONObject jsonObject) {
        String startTime = jsonObject.getString("startTime");
        String endTime = jsonObject.getString("endTime");
        String goodsId = jsonObject.getString("goodsId");
        String keywords = jsonObject.getString("keywords");
        int pageNum = jsonObject.getInteger("pageNum") == null ? 1 : jsonObject.getInteger("pageNum");
        int pageSize = jsonObject.getInteger("pageSize") == null ? 10 : jsonObject.getInteger("pageSize");
        PageHelper.startPage(pageNum, pageSize);
        List<FactoryOrderInfo> byOrderInfo = laundryFactoryService.findByOrderInfo(startTime, endTime, goodsId, keywords);
        for (FactoryOrderInfo factoryOrderInfo : byOrderInfo) {
            factoryOrderInfo.setTotal(JSBUtil.turnDoubleStr(factoryOrderInfo.getTotal()));
        }
        LOGGER.info("请求参数" + jsonObject + "返回参数" + byOrderInfo);
        return WebResponse.successData(byOrderInfo);
    }


    /**
     * 查询查账子订单
     */
    @PostMapping("orderInfos")
    public WebResponse orderInfos(@RequestBody JSONObject jsonObject) {
        String startTime = jsonObject.getString("startTime");
        String endTime = jsonObject.getString("endTime");
        String goodsId = jsonObject.getString("goodsId");
        String keywords = jsonObject.getString("keywords");
        String payId = jsonObject.getString("payId");
        int pageNum = jsonObject.getInteger("pageNum") == null ? 1 : jsonObject.getInteger("pageNum");
        int pageSize = jsonObject.getInteger("pageSize") == null ? 10 : jsonObject.getInteger("pageSize");
        PageHelper.startPage(pageNum, pageSize);
        List<FactoryOrderInfo> byOrderInfos = laundryFactoryService.findByOrderInfos(startTime, endTime, goodsId, keywords, payId);
        for (FactoryOrderInfo factoryOrderInfo : byOrderInfos) {
            factoryOrderInfo.setTotal(JSBUtil.turnDoubleStr(factoryOrderInfo.getTotal()));
        }
        LOGGER.info("请求参数" + jsonObject + "返回参数" + byOrderInfos);
        return WebResponse.successData(byOrderInfos);
    }

    /**
     * 下载
     *
     * @param request
     * @param response
     */
    @PostMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject jsonObject) {
        LOGGER.info("请求参数 request" + request + "请求参数 response" + response + "请求参数 jsonObject" + jsonObject);
        String startTime = jsonObject.getString("startTime");
        String endTime = jsonObject.getString("endTime");
        String goodsId = jsonObject.getString("goodsId");
        String keywords = jsonObject.getString("keywords");
        String payId = jsonObject.getString("payId");
        int pageNum = jsonObject.getInteger("pageNum") == null ? 1 : jsonObject.getInteger("pageNum");
        int pageSize = jsonObject.getInteger("pageSize") == null ? 10 : jsonObject.getInteger("pageSize");
        ExcelResponse xls = null;
        final String[] EXCEL_HEAD = {"用户", "订单单号", "顺丰单号(来)", "顺丰单号(回)", "骑手Id（来）", "骑手Id（回）", "衣服件数", "衣物类型", "订单价格", "收衣站点", "用户联系方式", "下单时间", "入库时间", "出库时间"};
        try {
            xls = new ExcelResponse(request, response, "订单查账表" + ".xls");
            xls.selectSheet("统计");
            xls.writeTitles(EXCEL_HEAD);
            //逻辑  list

//            PageHelper.startPage(pageNum, pageSize);
            List<FactoryOrderInfo> byOrderInfos = laundryFactoryService.findByOrderInfos(startTime, endTime, goodsId, keywords, payId);
            //遍历到excel
            for (FactoryOrderInfo list : byOrderInfos) {
                list.setTotal(JSBUtil.turnDoubleStr(list.getTotal()));
                if ("".equals(list.getOrderStatus())) {
//                    list.setOrderStatus();

                }
//                xls.setHSSFValidation();
                xls.writeRecord(
                        list.getUserAddressComeName(),
                        list.getOrderId(),
                        list.getSfId(),
                        list.getSfIds(),
                        list.getRiderId(),
                        list.getRiderBackId(),
                        list.getCount(),
                        list.getGoodsTitle(),
                        list.getTotal(),
                        list.getShopsName(),
                        list.getUserAddressComePhone(),
                        list.getPayTime(),
                        list.getBackCreateTime(),
                        list.getInTime()
                );
            }
        } catch (Exception e) {

            LOGGER.error("列表下载异常" + e.getMessage());
            try {
                AttachmentResponse.writeDownloadErrorResponse(response, "表列表下载异常");
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        } finally {
            if (xls != null) {

                xls.dump();
                xls.close();
            }
        }
    }


    /**
     * 补差价
     *
     * @param data
     * @return
     */
    @PostMapping("orderId")
    public WebResponse updGoodsId(@RequestBody String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        String goodsId = jsonObject.getString("goodsId");
        String serveId = jsonObject.getString("serveId");
        String orderId = jsonObject.getString("orderId");
        if (JSBUtil.isEmptyString(goodsId) || JSBUtil.isEmptyString(serveId) || JSBUtil.isEmptyString(orderId)) {
            return WebResponse.failOfParameter();
        }
        int d = laundryFactoryService.updGoodsId(goodsId, serveId, orderId);
        return WebResponse.successData(d);
    }


    /**
     * 获取订单信息（扫描枪扫描后根据支付id获取订单的全部信息）
     *
     * @return
     */
    @PostMapping("getScanOrderInfo/{payId}")
    public WebResponse getScanOrderInfo(@PathVariable String payId) {
        laundryFactoryService.getScanOrderInfo(payId);
        return WebResponse.success();
    }

    @PostMapping("/findruku")
    public WebResponse findruku(@RequestBody OrderInfoDtos orderInfoDtos) {
        Object findruku = laundryFactoryService.findruku(orderInfoDtos);
        return WebResponse.successData(findruku);
    }

    @PostMapping("/sss")
    public WebResponse sss(@RequestBody OrderInfoDtos orderInfoDtos) {
        if ("5".equals(orderInfoDtos.getOrderStatus())) {
            orderInfoDtos.setStatuss("5");
        }
        if ("1".equals(orderInfoDtos.getOrderStatus())) {
            orderInfoDtos.setStatuss("1");
        }
        int sss = laundryFactoryService.sss(orderInfoDtos);

        return WebResponse.successData("1");
    }

    @PostMapping("/ssss")
    public WebResponse ssss(@RequestBody String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        List list = jsonObject.getJSONArray("list");
        String orderStatus = jsonObject.getString("orderStatus");
        List<OrderInfoDtos> orderInfoDtos = new ArrayList<>();
        OrderInfoDtos orderInfoDtos1 = new OrderInfoDtos();
        orderInfoDtos1.setList(list);
        orderInfoDtos1.setOrderStatus(orderStatus);
        orderInfoDtos.add(orderInfoDtos1);
        int sss = laundryFactoryService.ssss(orderStatus, list);
        return WebResponse.successData("1");
    }


    @PostMapping("/findByList")
    public WebResponse findByList(@RequestBody FindByList findByList) {
        List<FindByList> byList = laundryFactoryService.findByList(findByList);
        if ("5".equals(findByList.getData())) {
            List<FindByList> var0 = packageList(byList);
            return WebResponse.successData(var0);
        }
        return WebResponse.successData(byList);
    }


    @PostMapping("updImg")
    public WebResponse updImg(@RequestBody String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        String orderId = jsonObject.getString("orderId");
        String postDevelopmentPhotos = jsonObject.getString("postDevelopmentPhotos");
        int i = laundryFactoryService.updImg(orderId, postDevelopmentPhotos);
        return WebResponse.successData(i);
    }

}